<template>
  <div class="Detail1">
    <div class="mixin">
      <div class="right">
        <div class="search-info">
          <div class="ans">
            <div class="search-result-area">
              <div class="operation-bar">
                <div>
                    <el-button type="danger" plain>删除记录</el-button>
                </div>
                <div class="right-operations">
                  <!-- 筛选下拉菜单 -->
                  <div class="filter-container">
                    <el-dropdown @command="handleFilterChange">
                      <span class="filter-text">
                        筛选
                        <i class="el-icon-arrow-down"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="week"
                          >近一周</el-dropdown-item
                        >
                        <el-dropdown-item command="month"
                          >近一月</el-dropdown-item
                        >
                        <el-dropdown-item command="year"
                          >近一年</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </el-dropdown>
                       <div class="pagination-controls" >
                      <i
                        class="iconfont icon-icon-zuoyouqiehuan-zuo"
                        @click="handlePrevPage"
                        :class="{ disabled: currentPage === 1 }"
                      ></i>
                      <div class="page-info">
                        {{ currentPage }}/{{ totalPages }}
                      </div>
                      <i
                        class="iconfont icon-icon-zuoyouqiehuan-you"
                        @click="handleNextPage"
                        :class="{ disabled: currentPage === totalPages }"
                      ></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="result-list-container">
            <CommonTable
              :tableData="searchResults"
              :columns="columns"
              :loading="isLoading"
              :showSelection="false"
            >
              <template #operation="scope">
                <el-button
                  type="text"
                  color="#409EFF"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </CommonTable>
            <!-- 加载状态提示
            <div class="loading-tip" v-if="isLoading">
              加载中...
            </div> -->

            <!-- 空状态 -->
            <div
              class="empty-state"
              v-if="searchResults.length === 0 && !isLoading"
            >
              <div class="aa">
                <img src="../assets/img/wu.png" alt="空状态" />
                <div class="empty-text">暂无数据</div>
              </div>
            </div>
          </div>

          <!-- 分页组件 -->
          <div class="pagination" v-if="searchResults.length > 0">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              :page-size="pageSize"
              layout="prev, pager, next, jumper"
              :total="totalCount"
              prev-text="上一页"
              next-text="下一页"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CommonTable from "../components/CommonTable.vue";
// import ResultList from "../components/SearchPage/ResultList.vue";

export default {
  components: {
    CommonTable,
  },
  data() {
    return {
      columns: [
        // 检索式列
        {
          label: "检索式", // 表头文字
          prop: "searchFormula", // 对应tableData中的字段名
          align: "left", // 左对齐（根据截图，内容偏左）
        },
        // 检索范围列
        {
          label: "检索范围",
          prop: "searchScope",
          align: "left",
        },
        // 检索时间列（支持排序）
        {
          label: "检索时间",
          prop: "searchTime",
          sortable: true, // 允许排序（对应截图中的箭头）
        },
        // 操作列（通过插槽自定义删除按钮）
        {
          label: "操作",
          slotName: "operation", // 插槽名称，用于父组件自定义内容
          width: 100,
        },
      ],
      types: "我的收藏",
      isLoading: false,
      currentPage: 1,
      totalCount: 0,
      pageSize: 10,
      searchResults: [],
      selectedIds: [],
      filterTime: null,
    };
  },
  computed: {
    totalPages() {
      if (this.totalCount === 0) return 1;
      return Math.ceil(this.totalCount / this.pageSize);
    },
  },
  methods: {
     handleDelete(row) {
      console.log('删除行数据：', row);
      // 实际业务中：调用接口删除 + 刷新表格数据
      this.searchResults = this.searchResults.filter(item => item.id !== row.id);
    },
     handlePrevPage() {
    if (this.currentPage > 1) {
      this.currentPage--;
      this.fetchData();
    }
  },

  // 下一页
  handleNextPage() {
    if (this.currentPage < this.totalPages) {
      this.currentPage++;
      this.fetchData();
    }
  },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.selectedIds = [];
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.selectedIds = [];
      this.fetchData();
    },
    handleFilterChange(timeRange) {
      this.filterTime = timeRange;
      this.currentPage = 1;
      this.selectedIds = [];
      this.fetchData();
    },
    handleItemCancelCollection(id) {
      this.$confirm("确定要取消此项收藏吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.searchResults = this.searchResults.filter(
            (item) => item.id !== id
          );
          this.selectedIds = this.selectedIds.filter((itemId) => itemId !== id);
          this.totalCount--;
          this.$message.success("取消收藏成功");
        })
        .catch(() => {
          this.$message.info("已取消操作");
        });
    },
    async fetchData() {
      if (this.isLoading) return;

      try {
        this.isLoading = true;
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          filterTime: this.filterTime,
        };

        // 模拟API调用
        const response = await this.mockApi(params);
        this.searchResults = response.data;
        this.totalCount = response.total;
      } catch (error) {
        console.error("获取数据失败:", error);
        this.searchResults = [];
        this.totalCount = 0;
      } finally {
        this.isLoading = false;
      }
    },
    mockApi(params) {
      return new Promise((resolve) => {
        setTimeout(() => {
          let mockResults = Array.from({ length: params.pageSize }, (_, i) => {
            const id = (params.page - 1) * params.pageSize + i + 1;

            let date;
            if (params.filterTime === "week") {
              const days = Math.floor(Math.random() * 7);
              date = new Date();
              date.setDate(date.getDate() - days);
            } else if (params.filterTime === "month") {
              const days = Math.floor(Math.random() * 30);
              date = new Date();
              date.setDate(date.getDate() - days);
            } else if (params.filterTime === "year") {
              const days = Math.floor(Math.random() * 365);
              date = new Date();
              date.setDate(date.getDate() - days);
            } else {
              date = new Date(
                2021,
                Math.floor(Math.random() * 4),
                Math.floor(Math.random() * 28) + 1
              );
            }

            const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1)
              .toString()
              .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;

            return {
              id,
              title: `收藏项 ${id}`,
              content: `这是收藏项${id}的详细描述内容`,
              source: `来源${Math.floor(Math.random() * 5) + 1}`,
              time: formattedDate,
              collectTimestamp: date.getTime(),
            };
          });

          resolve({
            data: mockResults,
            total: Math.floor(Math.random() * 100) + 100,
          });
        }, 300);
      });
    },
    handleSelectItem(checked, id) {
      if (checked) {
        if (!this.selectedIds.includes(id)) {
          this.selectedIds.push(id);
        }
      } else {
        this.selectedIds = this.selectedIds.filter((itemId) => itemId !== id);
      }
    },
  },
  created() {
    this.fetchData();
  },
};
</script>

<style lang="scss" scoped>
  .pagination-controls {
    margin-left: 34px;
      display: flex;
      align-items: center;
      font-size: 18px;
      color: #333;

      .page-info {
        padding: 0 17px;
      }

      i {
        cursor: pointer;

        &.disabled {
          cursor: not-allowed;
          color: #ccc;
        }
      }
    }
.pagination {
  display: flex;
  justify-content: flex-end;
}

.loading-tip,
.no-more-tip {
  text-align: center;
  padding: 20px 0;
  color: #666;
  font-size: 14px;
}

.no-more-tip {
  color: #999;
}

::v-deep .el-pager li {
  background-color: #f9faff;
}

::v-deep .el-pagination .btn-next,
.el-pagination .btn-prev {
  background-color: #f9faff;
}

::v-deep .el-dropdown-menu {
  min-width: 100px;
}
.ans {
  width: 1060px;
  background: #ffffff;
  box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.07);
  border-radius: 4px;
  margin-bottom: 20px;

  .search-result-area {
    margin-bottom: 20px;

    .operation-bar {
      display: flex;
      justify-content:space-between;
      align-items: center;
      padding: 30px 20px;

      .right-operations {
        display: flex;
        align-items: center;

        .filter-container {
          display: flex;
          .filter-text {
            font-size: 18px;
            color: #333;
            cursor: pointer;
            display: inline-flex;
            align-items: center;

            i {
              margin-left: 5px;
              font-size: 14px;
            }
          }
        }
      }
    }
  }
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.loading-tip {
  text-align: center;
  padding: 20px 0;
  color: #666;
  font-size: 14px;
}

.search-info {
  width: 1060px;
}

.result-list-container {
  width: 1060px;
  border: 1px solid #e0e0e0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 160px 0;
  color: #999;

  .aa {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 18px;
    color: #666666;

    .empty-text {
      margin-top: 18px;
    }
  }
}

::v-deep .el-pager li {
  background-color: #f9faff;
}

::v-deep .el-pagination .btn-next,
.el-pagination .btn-prev {
  background-color: #f9faff;
}

::v-deep .el-dropdown-menu {
  min-width: 100px;
}
</style>
